package org.sasha.roulette.data;

import java.io.Serializable;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Singleton;

import com.vaadin.data.Item;
import com.vaadin.data.util.sqlcontainer.SQLContainer;

@SuppressWarnings("serial")
@Singleton
public class ChartHelper implements Serializable {

    private final DBHelper dbHelper;
    
    @Inject
    public ChartHelper(final DBHelper dbHelper) {
        this.dbHelper = dbHelper;
    }
    
    public List<Double> getOccurenceList() {
        final SQLContainer container = dbHelper.getOccurenceContainer();
        final List<Integer> order = Arrays.asList(RouletteConstant.ORDER);
        final LinkedList<Double> result = new LinkedList<Double>(Collections.nCopies(order.size(), 0d));
        Object id = container.firstItemId();
        while (id != null) {
            final Item item = container.getItem(id);
            int value = (Integer)item.getItemProperty("VALUE").getValue();
            int occurence = ((Long)item.getItemProperty("OCCURENCE").getValue()).intValue();
            int index = order.indexOf(value);
            result.set(index, occurence * 1d);
            id = container.nextItemId(id);
        }
        return result;
    }

    public int getOddCount() {
        return countParity(true);
    }

    public int getEvenCount() {
        return countParity(false);
    }
    
    private int countParity(boolean odd) {
        final SQLContainer container = dbHelper.getSpinContainer();
        Object id = container.firstItemId();
        int result = 0;
        while (id != null) {
            final Item item = container.getItem(id);
            int value = (Integer)item.getItemProperty("VALUE").getValue();
            boolean incr = odd ? value % 2 != 0 : value % 2 == 0;  
            if (incr) {
                ++result;
            }
            id = container.nextItemId(id);
        }
        return result;
    }

    public int[] getThirdsFrequencies() {
        final SQLContainer container = dbHelper.getSpinContainer();
        Object id = container.firstItemId();
        int[] result = new int[] {0,0,0};
        while (id != null) {
            final Item item = container.getItem(id);
            int value = (Integer)item.getItemProperty("VALUE").getValue();
            if (value >= 1 && value <= 12) {
                ++result[0];
            } else if (value >= 13 && value <= 24) {
                ++result[1];
            } else if (value >= 25 && value <= 36) {
                ++result[2];
            }
            id = container.nextItemId(id);
        }
        return result;
    }
}
